import json
import logging
import os

from django.views import View
from django.core.paginator import Paginator, InvalidPage
from django.http import HttpRequest, JsonResponse

from app.models import CityModel, MachineRoomModel, HostModel
from app.form import CityForm, MachineRoomForm, HostForm, PutHostForm

logger = logging.getLogger('django')


class CityView(View):
    def get(self, request: HttpRequest) -> JsonResponse:
        page = request.GET.get('page', 1)
        per_page = request.GET.get('per_page', 10)
        paginator: Paginator = Paginator(CityModel.objects.values('id', 'name'), per_page)
        try:
            data = paginator.page(page)
        except InvalidPage:
            data = []
        return JsonResponse({'code': 200, 'data': [
            item for item in data
        ], 'count': paginator.count})

    def post(self, request: HttpRequest) -> JsonResponse:
        form = CityForm(data=json.loads(request.body))
        if form.is_valid():
            try:
                CityModel.objects.create(**form.cleaned_data)
                return JsonResponse({'code': 200})
            except Exception as e:
                logger.error(e)
                return JsonResponse({'code': 500, 'error': "添加失败！"})
        return JsonResponse({'code': 400, 'error': form.error})

    def put(self, request: HttpRequest) -> JsonResponse:
        data = json.loads(request.body)
        nid = data.pop('id')
        form = CityForm(data=data)
        if form.is_valid():
            try:
                city = CityModel.objects.get(id=nid)
                city.name = form.cleaned_data.get('name')
                city.save()
                return JsonResponse({'code': 200})
            except CityModel.DoesNotExist:
                return JsonResponse({'code': 400, 'error': '城市数据不存在！'})
            except Exception as e:
                logger.error(e)
                return JsonResponse({'code': 500, 'error': '修改失败！'})
        return JsonResponse({'code': 400, 'error': form.error})

    def delete(self, request: HttpRequest) -> JsonResponse:
        try:
            city = CityModel.objects.get(id=request.GET.get('id'))
            city.delete()
            return JsonResponse({'code': 200})
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 500, 'error': '删除失败！'})


class MachineRoomView(View):
    def get(self, request: HttpRequest) -> JsonResponse:
        page = request.GET.get('page', 1)
        per_page = request.GET.get('per_page', 10)
        paginator: Paginator = Paginator(MachineRoomModel.objects.values('id', 'city'), per_page)
        try:
            data = paginator.page(page)
        except InvalidPage:
            data = []
        return JsonResponse({'code': 200, 'data': [
            item for item in data
        ], 'count': paginator.count})

    def post(self, request: HttpRequest) -> JsonResponse:
        form = MachineRoomForm(data=json.loads(request.body))
        if form.is_valid():
            try:
                MachineRoomModel.objects.create(city_id=form.cleaned_data['city'])
                return JsonResponse({'code': 200})
            except Exception as e:
                logger.error(e)
                return JsonResponse({'code': 500, 'error': "添加失败！"})
        return JsonResponse({'code': 400, 'error': form.error})

    def put(self, request: HttpRequest) -> JsonResponse:
        data = json.loads(request.body)
        nid = data.pop('id')
        form = MachineRoomForm(data=data)
        if form.is_valid():
            try:
                machine_room = MachineRoomModel.objects.get(id=nid)
                machine_room.city_id = form.cleaned_data.get('city')
                machine_room.save()
                return JsonResponse({'code': 200})
            except MachineRoomModel.DoesNotExist:
                return JsonResponse({'code': 400, 'error': '机房数据不存在！'})
            except Exception as e:
                logger.error(e)
                return JsonResponse({'code': 500, 'error': '修改失败！'})
        return JsonResponse({'code': 400, 'error': form.error})

    def delete(self, request: HttpRequest) -> JsonResponse:
        try:
            machine_room = MachineRoomModel.objects.get(id=request.GET.get('id'))
            machine_room.delete()
            return JsonResponse({'code': 200})
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 500, 'error': '删除失败！'})


class HostView(View):
    def get(self, request: HttpRequest) -> JsonResponse:
        page = request.GET.get('page', 1)
        per_page = request.GET.get('per_page', 10)
        paginator: Paginator = Paginator(HostModel.objects.all(), per_page)
        try:
            data = paginator.page(page)
        except InvalidPage:
            data = []
        return JsonResponse({'code': 200, 'data': [
            {
                'id': item.id,
                'machine_room': item.machine_room_id,
                'ip': item.ip,
                'cpu': item.cpu,
                'memory': item.memory,
                'motherboard': item.motherboard,
                'hard_disk': item.hard_disk,
                'is_use': item.is_use
            } for item in data
        ], 'count': paginator.count})

    def post(self, request: HttpRequest) -> JsonResponse:
        form = HostForm(data=json.loads(request.body))
        if form.is_valid():
            try:
                HostModel.objects.create(**form.cleaned_data)
                return JsonResponse({'code': 200})
            except Exception as e:
                logger.error(e)
                return JsonResponse({'code': 500, 'error': "添加失败！"})
        return JsonResponse({'code': 400, 'error': form.error})

    def put(self, request: HttpRequest) -> JsonResponse:
        data = json.loads(request.body)
        nid = data.get('id')
        form = PutHostForm(data=data)
        if form.is_valid():
            try:
                host = HostModel.objects.get(id=nid)
                form_data = form.cleaned_data
                form_data.pop('old_password')
                for key, value in form_data.items():
                    setattr(host, key, value)
                host.save()
                return JsonResponse({'code': 200})
            except HostModel.DoesNotExist:
                return JsonResponse({'code': 400, 'error': '主机数据不存在！'})
            except Exception as e:
                logger.error(e)
                return JsonResponse({'code': 500, 'error': '修改失败！'})
        return JsonResponse({'code': 400, 'error': form.error})

    def delete(self, request: HttpRequest) -> JsonResponse:
        try:
            host = HostModel.objects.get(id=request.GET.get('id'))
            host.delete()
            return JsonResponse({'code': 200})
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 500, 'error': '删除失败！'})


class PingHostView(View):
    def get(self, request: HttpRequest) -> JsonResponse:
        try:
            host = HostModel.objects.get(id=request.GET.get('host_id'))
        except HostModel.DoesNotExist:
            return JsonResponse({'code': 400, 'error': '主机不存在！'})
        result = os.system(f'ping {host.ip}')
        return JsonResponse({'code': 200, 'result': not bool(result)})
